import os
from dotenv import load_dotenv
import requests
import json

# 加载环境变量
load_dotenv()
api_key = os.getenv("DEEPSEEK_API_KEY")
endpoint = os.getenv("DEEPSEEK_API_BASEURL")

headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json"
}
payload = {
    "model": "deepseek-chat",
    "messages": [{"role": "user", "content": "下午好！"}],
    "stream": True  # 启用流式响应
}

# 发送请求并处理流式响应
with requests.post(endpoint, json=payload, headers=headers, stream=True) as res:
    for line in res.iter_lines():
        if line:
            try:
                # 解码并解析 JSON
                decoded_line = line.decode("utf-8")
                data = json.loads(decoded_line.split("data: ")[1])  # 提取 JSON 数据
                content = data["choices"][0]["delta"].get("content", "")
                if content:
                    print(content, end="")  # 打印流式输出
            except (json.JSONDecodeError, IndexError, KeyError) as e:
                # print(f"解析错误: {e}")
                pass  # 忽略解析错误


